package com.wangjie.simple;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * @author jieshao
 * @date 2022/5/13 14:33
 *
 * 1. 两数之和
 */
public class Test01 {
    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 5};
        int target = 3;
        int[] res1 = twoSum1(arr, target);
        int[] res2 = twoSum2(arr, target);
        System.out.println(Arrays.toString(res1));
        System.out.println(Arrays.toString(res2));
    }

    public static int[] twoSum1(int[] nums, int target) {
        for (int i = 0; i < nums.length; i++) {
            for (int j = i + 1; j < nums.length; j++) {
                if (nums[i] + nums[j] == target) {
                    return new int[]{i, j};
                }
            }
        }
        return new int[0];
    }

    public static int[] twoSum2(int[] nums, int target) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            if (map.containsKey(target - nums[i])) {
                return new int[]{map.get(target - nums[i]), i};
            }
            map.put(nums[i], i);
        }
        return new int[0];
    }
}